package com.zz.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zz.domain.User;
import com.zz.dto.LoginToken;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 工具类
 * */
public class VideoUtil {
    //获取用户真实的地址
    private  static   String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    //生成LoginToken对象
    public static LoginToken generateLoginToken(HttpServletRequest request, User user){
        LoginToken loginToken = new LoginToken();
        loginToken.setIp(getIpAddr(request));
        loginToken.setNow(DateUtil.now());
        loginToken.setUserAgent(request.getHeader("user-agent"));
        loginToken.setUser(user);
        return  loginToken;
    }

    //把cookie里面token取出来
    public static  String getCookieTokenValue(Cookie[] cookies){

        String cookieTokenValue = "";
        if (cookies == null){
            return  cookieTokenValue;
        }
        for (Cookie cookie: cookies){
            String cookieName = cookie.getName();
            if ( Constants.COOKIE_TOKEN_KEY.equals(cookieName)){
                cookieTokenValue = cookie.getValue();
            }
        }
        return  cookieTokenValue ;
    }


    //效验cookie里面的键,符不符合要求
    public static Boolean checkLoginToken(String CookieTokenValue,HttpServletRequest request){
        if (StrUtil.isEmpty(CookieTokenValue)){
            //没有登录凭证,需要重新登录
            return false;
        }
        ServletContext application = request.getServletContext();
        HashMap<String,LoginToken> tokenHashMap = (HashMap<String, LoginToken>) application.getAttribute(Constants.AUTO_LOGIN_TOKEN);
        if (ObjectUtil.isEmpty(tokenHashMap)){
            return false ; //如果Map里面没东西
        }
        LoginToken loginToken  = tokenHashMap.get(CookieTokenValue);
        if (ObjectUtil.isEmpty(loginToken)){
            return  false;
        }
        DateTime  now =  DateUtil.parse(DateUtil.now());
        DateTime loginNow = DateUtil.parse(loginToken.getNow());
        //如果超过了48小时,就说明失效了
        if (! (now.getTime() - loginNow.getTime() > 172800000) ){
            return  false ;
        }
        if (loginToken.generateToken().equals(CookieTokenValue)){
            return  true;
        }else {
            return false;
        }
    }


}
